<!--阿里人脸数据库页-->
<template>
    <div style="height: 100%;">

        <m-page-list
                ref="pageListRef"
                :option="option"
                :page="page"
                :total="total"
                :table-data="tableData"
                :table-loading="tableLoading"
                v-model:value="query"
                @h-btn-click="hBtnClick"
                @col-btn-click="colBtnClick"
                @search-data="searchData"
        />

        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>

        <m-progress ref="progressRef">
            <template #footer>
                <div v-show="isShowStopBtn">
                    <el-button v-show="!isDeleteStop" type="primary" @click="stopDelete">停止</el-button>
                    <el-button v-show="isDeleteStop" type="default" @click="progressRef.close()">关闭</el-button>
                </div>
            </template>
        </m-progress>
    </div>

</template>

<script setup>

  import {ref,reactive,onMounted,nextTick} from 'vue'
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  import MProgress from '@/components/common/Progress/Progress'
  //请求
  import {getAliyunFaceDB,getParameter,deleteAliyunFacePic} from '@/request/api/basicData'

  import {usePageList} from "../../composables/pageList";

  //引用类型字段参数
  import {refOpt} from "../const";

  let opts = {
    // auth_id: 'stop',
    getApi: getAliyunFaceDB,
    // addApi:addDriverData,
    // editApi:editDriverData,
    // delApi:delDriverData,
    idKey: 'driver_no',
  };
  let {option,page,total,tableLoading,tableData,query,dialogRef,dialogShow,dialogData,
    hBtnClick,colBtnClick,searchData,dialogOption,dialogConfirm,getDataList} = usePageList(opts);

  option.hLBtns = [];
  // 表头右侧按钮
  option.hRBtns.unshift({title: '清理过期人脸库',id: 'clear',type: 'primary',event: () =>{clearFace();}})

  //  查询条件参数配置
  option.conditions = [
    {label: '数据库名',type: 'text',field_id: 'db_name',col: 24},
  ];
  // 表格列显示参数配置
  option.cols = [
    {prop: 'db_name', label: '数据库名',},
    {prop: 'effective_time_end_min', label: '数据有效期止最小值',},
    {prop: 'effective_time_end_max', label: '数据有效期止最大值',},
    {prop: 'remark', label: '备注',},
    {prop: 'data_size', label: '数据容量',},
    {prop: 'used_size', label: '已用量',},
    {prop: 'unused_size', label: '未用量',},
    {prop: 'is_success', label: '成功标识',type: 'bool'},
    {prop: 'modify_name', label: '修改员名',},
    {prop: 'modify_time', label: '修改时间',},
    {prop: 'input_name', label: '录入员名',},
    {prop: 'input_time', label: '录入时间',},
  ];
  option.colBtns = [];

  option.tableSelection = true;


  // 新增编辑弹窗录入项配置
  dialogOption.fieldList = [
    {field_id: 'db_name', label: '数据库名',type: 'text',col: 3},
    {field_id: 'remark', label: '备注',type: 'textarea',col: 3},
  ];


  const pageListRef = ref(null),
    progressRef = ref(null),
    isDeleteStop = ref(null),
    isShowStopBtn = ref(false),     // 显示停止按钮标识
    errmsg = reactive([]);
  const clearFace = function () {
    let rows = pageListRef.value.getSelectionRows();
    console.log(rows);
    if (!rows.length) {
      ElMessage({type: 'warning', message: '请先选择数据行'});
      return;
    }

    ElMessageBox.confirm('确定清理过期人脸数据？', '清理', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: async (action) => {
        if (action === 'confirm') {
          errmsg.length = 0;
          let dataArr = [];
          await formatDeleteData(rows).then(data => dataArr = data || []);
          console.log(dataArr);
          if (!dataArr.length){
            ElMessage.warning('没有需要清理的照片');
            return
          }

          isShowStopBtn.value = true;
          isDeleteStop.value = false;
          progressRef.value.setProgress('loading','正在清理中');

          eachDelete(dataArr,0, deleteAliyunFacePic,(res, index) => {
            progressRef.value.setPercentage(Math.ceil((index + 1) / dataArr.length * 100))
            if (res.errcode != 0) {
              errmsg.push(`${dataArr[index].db_name}：${res.errmsg}`);
            }

            // 最后一条数据
            if (index === dataArr.length - 1) {
              console.log(errmsg);
              let type = '', title = '';
              if (errmsg.length) {
                type = 'error';
                title = '清理出错'
              } else {
                type = 'success';
                title = '清理成功';
              }
              isDeleteStop.value = false;
              isShowStopBtn.value = false;
              progressRef.value.setProgress(type, title, errmsg);
              getDataList();
            }
          })
        }
      }
    })
  }

  const eachDelete = (dataArr,index,requestFn,callback) =>{
    if (isDeleteStop.value) return;
    if (dataArr.length < index+1) return
    let data = dataArr[index];

    requestFn && requestFn(data).then(res =>{
      callback && callback(res,index);
      eachDelete(dataArr,index+1,requestFn,callback)
    })
  }

  //  停止上传
  const stopDelete = () => {
    isDeleteStop.value = true;
    progressRef.value.setProgress('stop','停止清理')
  }

  const formatDeleteData = (row) =>{
    return new Promise(async resolve => {
      getParameter({id: 'AliyunFaceMaxBatchSize'}).then(res =>{
        let data = res.row[0],
          size = data && data.parameter_value || 10,
          paramArr = [];
        row.forEach(item =>{
          let {db_name,used_size} = item;
          if (used_size > 0) {
            let times = Math.ceil(used_size / size);
            for (let i = 0;i < times; i++){
              paramArr.push({db_name, batch_size: size})
            }
          }
        });
        resolve(paramArr);

      })
    })
  }

</script>

